#include <iostream>
#include <string.h>

using std::cout;
using std::endl;
using std::string;

class String
{
public:
	String()
    : _pstr(new char[7])
    {
        strcpy(_pstr,"string1");
        cout<<"无参构造"<<endl;
    }
	String(const char *pstr)
    : _pstr(new char[strlen(pstr)+1])
    {
        strcpy(_pstr,pstr);
        cout<<"有参构造"<<endl;
    }

    String(const String &rhs)
    : _pstr(new char[strlen(rhs._pstr)+1])
    {
        strcpy(_pstr, rhs._pstr);
        cout<<"拷贝构造"<<endl;
    }

	String &operator=(const String &rhs){
        if(this!=&rhs){
            delete []_pstr;
            _pstr=nullptr;
            _pstr=new char[strlen(rhs._pstr)+1];

            strcpy(_pstr,rhs._pstr);
            cout<<"赋值运算符函数"<<endl;
        }

        return *this;
    }

    ~String(){
        delete []_pstr;
        cout<<"析构函数"<<endl;
        _pstr=nullptr;
    }

    void print(){
        cout<<_pstr<<endl;
    }
    
    size_t length() const{
        return strlen(_pstr);
    }

    const char * c_str() const{
        return _pstr;
    };

private:
	char * _pstr;
};


int main()
{
	String str1;
	str1.print();
    cout<<str1.length()<<endl;
	cout<<endl;

	String str2 = "Hello,world";
	String str3("wangdao");
	
	str2.print();		
	str3.print();	
    cout<<str2.length()<<endl;
    cout<<str3.length()<<endl;
    cout<<endl;
	
	String str4 = str3;
	str4.print();
    cout<<str4.c_str()<<endl;
    cout<<endl;
	
	str4 = str2;
	str4.print();
    cout<<endl;
	
	return 0;
}


